package com.hongkuncheng.cms.helper;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.FactorySession;
import org.springframework.beans.factory.annotation.Value;
import com.alibaba.fastjson.*;

/**
 * 微博帮助类
 *
 * @author 洪坤成
 */
public class WeiboHelper {

    public static FactorySession factorySession;
    public static String appKey;
    public static String appSecret;
    public static String callbackUrl = "/interfaces/weibo/callback";

    public static void initial(String appKey, String appSecret) {
        WeiboHelper.appKey = appKey;
        WeiboHelper.appSecret = appSecret;
    }

    // 获取AccessToken
    public static String getAccessToken(String host, String code) throws JSONException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("client_id", appKey);
        params.put("client_secret", appSecret);
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        params.put("redirect_uri", host + callbackUrl);
        String result = HttpHelper.post("https://api.weibo.com/oauth2/access_token", params);
        JSONObject jsonobj = JSON.parseObject(result);
        return jsonobj.getString("access_token");
    }

    // 发送文本
    public static void sendText(String token, String text) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", token);
        params.put("status", text);
        HttpHelper.post("https://api.weibo.com/2/statuses/update.json", params);
    }

    // 发送图文
    public static void sendTextAndImage(String token, String text, File image) {
        Map<String, Object> params = new HashMap<String, Object>();
        System.out.println("token:" + token);
        params.put("access_token", token);
        params.put("status", text);
        params.put("pic", image);
        String r = HttpHelper.post("https://upload.api.weibo.com/2/statuses/upload.json", params);
        System.out.println("r:" + r);
    }

}
